import { t } from 'i18next'
import React, { useEffect, useState } from 'react'
import { Button, DatePicker, Input } from '@kedacom/react-next'
import { Wrap, Header, IconArrow, IconSearch, EllipsisDiv } from './style'
import { transQualityItem } from './translator'
import { Alert } from '@/components/Alert'
import dayjs from '@/plugins/dayjs'
import { StyledBottom, ErrorTips, IconNotFound } from '../../style'
import { API_MEETING_PREFIX } from '@/utils/constant'
import { meetingStatus } from '@/api/global/interface'
import Table, { ColumnProps } from '@/components/Table'
import { useRequest } from 'ahooks'
import { fetchGetJdbStatus, fetchGetQuality, IQualityItem, IMeetingInfo } from '@/api/meetingSpace'
import type { Dayjs } from 'dayjs'

const PageSize = 10

interface ISort {
	mt_name: 'desc' | 'asc' | null
	event_time: 'desc' | 'asc'
}

function makeSort(sort: ISort) {
	let sortArr = []
	for (const [key, val] of Object.entries(sort)) {
		if (val) {
			sortArr.push(`${key}:${val}`)
		}
	}
	return sortArr.join(',')
}
/** 检测记录 */
const Quality = ({ meetingInfo }: { meetingInfo: IMeetingInfo }) => {
	const [auth, setAutn] = useState(false)
	const [initCondition, setInitCondition] = useState({
		search: '',
		start_time: meetingInfo.startTime,
		end_time: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
	})
	const [isCanSearch, setIsCanSearch] = useState(false)
	const [condition, setCondition] = useState({
		search: '',
		start_time: meetingInfo.startTime,
		end_time: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
	})
	const [pager, setPage] = useState({ total: 1, page: 1, size: PageSize })
	const [sort, setSort] = useState<ISort>({
		mt_name: null,
		event_time: meetingInfo.status === meetingStatus.BEING ? 'desc' : 'asc',
	})
	const [tableData, setTableData] = useState<IQualityItem[]>([])
	const Columns: ColumnProps<IQualityItem>[] = [
		{
			dataKey: 'mt_name',
			title: t('终端名称'),
			sort: sort.mt_name,
			isHideSortFirstly: true,
			onSort: (e, status) => {
				setSort({ mt_name: status, event_time: sort.event_time })
				run(meetingInfo.meetingMoid, {
					search: condition.search,
					start_time: condition.start_time,
					end_time: condition.end_time,
					start: 0,
					count: PageSize,
					sort: makeSort({ mt_name: status, event_time: sort.event_time }),
				})
			},
		},
		{
			dataKey: 'event_time',
			title: t('发生时间'),
			width: 160,
			sort: sort.event_time,
			onSort: (e, status: 'asc' | 'desc') => {
				setSort({ event_time: status, mt_name: sort.mt_name })
				run(meetingInfo.meetingMoid, {
					search: condition.search,
					start_time: condition.start_time,
					end_time: condition.end_time,
					start: 0,
					count: PageSize,
					sort: makeSort({
						event_time: status,
						mt_name: sort.mt_name,
					}),
				})
			},
		},
		{
			dataKey: 'recovery_time',
			title: t('恢复时间'),
			width: 180,
		},
		{
			dataKey: 'description',
			title: t('异常类型'),
			width: 130,
		},
		{
			dataKey: 'suggestion',
			title: t('解决方案'),
			render: (rowData, value) => {
				return <EllipsisDiv title={value}>{value}</EllipsisDiv>
			},
		},
	]
	const { run, runAsync } = useRequest(fetchGetQuality, {
		manual: true,
		onSuccess: (res) => {
			if (res.success) {
				setPage((val) => ({ ...val, total: res.total }))
				const list = res.info.map((x) => transQualityItem(x))
				setTableData(list)
			}
			if (tableData.length === 0) {
				setIsCanSearch(false)
			}
		},
	})
	useEffect(() => {
		fetchGetJdbStatus(meetingInfo.meetingMoid).then((res) => {
			if (res.success && res.data) {
				setAutn(true)
			}
		})
	}, [])
	useEffect(() => {
		//会议当前状态只会在最上级请求后变更一次，获取到真实状态后 执行一次初始化
		if (meetingInfo.status && auth) {
			const end_time = dayjs().format('YYYY-MM-DDTHH:mm:ss')
			setCondition({
				search: '',
				start_time: meetingInfo.startTime,
				end_time,
			})
			setInitCondition({
				search: '',
				start_time: meetingInfo.startTime,
				end_time,
			})
			setPage({ total: 1, page: 1, size: PageSize })
			let sortData = {
				mt_name: null,
				event_time: (meetingInfo.status === meetingStatus.BEING ? 'desc' : 'asc') as any,
			}
			setSort(sortData)
			run(meetingInfo.meetingMoid, {
				search: '',
				start_time: meetingInfo.startTime,
				end_time,
				start: 0,
				count: PageSize,
				sort: makeSort(sortData),
			})
		}
	}, [meetingInfo.status, auth])
	const handleChangeInput = (e: React.ChangeEvent<HTMLInputElement>, value: string) => {
		setCondition((val) => ({ ...val, search: value.trim() }))
	}
	const handleBlurInput = (e: React.ChangeEvent<HTMLInputElement>, value: string) => {
		if (initCondition.search !== value) {
			setIsCanSearch(true)
		} else {
			setIsCanSearch(false)
		}
	}
	const handleChangeDate = (key: 'start_time' | 'end_time', value: Dayjs) => {
		const time = value?.format('YYYY-MM-DDTHH:mm:ss')
		if (key === 'start_time') {
			let flag = value?.isBefore(dayjs(condition.end_time))
			if (!flag) {
				Alert(t('开始时间不能晚于结束时间'))
				return
			}
		} else {
			let flag = value?.isAfter(dayjs(condition.start_time))
			if (!flag) {
				Alert(t('结束时间不能早于开始时间'))
				return
			}
		}
		if (initCondition[key] === time) {
			setIsCanSearch(false)
		} else {
			setIsCanSearch(true)
		}
		setCondition((val) => ({ ...val, [key]: time }))
	}
	const handleChangePage = (pageIndex: number) => {
		setPage((val) => ({ ...val, page: pageIndex }))
		run(meetingInfo.meetingMoid, {
			search: condition.search,
			start_time: condition.start_time,
			end_time: condition.end_time,
			start: PageSize * (pageIndex - 1),
			count: PageSize,
			sort: makeSort(sort),
		})
	}
	const handleSearch = () => {
		setInitCondition((val) => {
			return Object.assign({}, val, condition)
		})
		runAsync(meetingInfo.meetingMoid, {
			search: condition.search,
			start_time: condition.start_time,
			end_time: condition.end_time,
			start: 0,
			count: PageSize,
			sort: makeSort(sort),
		}).then(() => {
			setPage((val) => ({ ...val, pageIndex: 1 }))
		})
	}
	const handleExport = () => {
		window.open(
			`${API_MEETING_PREFIX}/api/inner/ops/diagnose/conf/${meetingInfo.meetingMoid}/all/export/?search=${condition.search}&start_time=${condition.start_time}&end_time=${condition.end_time}`
		)
	}
	return (
		<Wrap>
			{auth ? (
				<>
					<Header>
						<div>
							<Input
								width={150}
								style={{ marginRight: 15 }}
								maxLength={128}
								placeholder={t('请输入终端名称')}
								value={condition.search}
								onChange={handleChangeInput}
								onBlur={handleBlurInput}
							/>
							<DatePicker
								picker="datetime"
								style={{ marginRight: 12 }}
								onChange={(e, str, val) => handleChangeDate('start_time', val)}
								value={condition.start_time}
								timeFormat="HH:mm"
								i18n={{
									confirm: t('确认'),
									year: t('年'),
									month: [
										t('1月'),
										t('2月'),
										t('3月'),
										t('4月'),
										t('5月'),
										t('6月'),
										t('7月'),
										t('8月'),
										t('9月'),
										t('10月'),
										t('11月'),
										t('12月'),
									],
									week: [t('日'), t('一'), t('二'), t('三'), t('四'), t('五'), t('六')],
								}}
							/>
							<IconArrow style={{ marginRight: 12 }} />
							<DatePicker
								picker="datetime"
								style={{ marginRight: 20 }}
								onChange={(e, str, val) => handleChangeDate('end_time', val)}
								value={condition.end_time}
								timeFormat="HH:mm"
								i18n={{
									confirm: t('确认'),
									year: t('年'),
									month: [
										t('1月'),
										t('2月'),
										t('3月'),
										t('4月'),
										t('5月'),
										t('6月'),
										t('7月'),
										t('8月'),
										t('9月'),
										t('10月'),
										t('11月'),
										t('12月'),
									],
									week: [t('日'), t('一'), t('二'), t('三'), t('四'), t('五'), t('六')],
								}}
							/>
							<IconSearch className={`${!isCanSearch ? 'disabled' : ''}`} onClick={handleSearch} />
						</div>
						<Button disabled={tableData.length === 0} onClick={handleExport}>
							{t('导出')}
						</Button>
					</Header>
					<Table
						className="quality-table"
						height={488}
						tableDataList={tableData}
						columns={Columns}
						showOrderColumn={false}
						showSelectColumn={false}
						pager={pager}
						onPageChange={handleChangePage}
						i18n={{ order: t('序号') }}
					/>
				</>
			) : (
				<ErrorTips>
					<IconNotFound />
					{t('未配置会议大数据服务器，无相关记录')}。
				</ErrorTips>
			)}
			<StyledBottom />
		</Wrap>
	)
}
export default Quality
